package com.example.warehouse.contrallor;


import com.example.warehouse.entity.Auth;
import com.example.warehouse.entity.LoginUser;
import com.example.warehouse.entity.Result;
import com.example.warehouse.entity.User;
import com.example.warehouse.service.AutoService;
import com.example.warehouse.service.userService;
import com.example.warehouse.utils.CurrentUser;
import com.example.warehouse.utils.DigestUtil;
import com.example.warehouse.utils.TokenUtils;
import com.example.warehouse.utils.WarehouseConstants;
import com.google.code.kaptcha.Producer;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class contrallorLogin {
    @Resource(name = "captchaProduce")
    private Producer producer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/captcha/captchaImage")
    public void capchaImage(HttpServletResponse response) throws Exception {

        String text = producer.createText();
        BufferedImage image = producer.createImage(text);

        redisTemplate.opsForValue().set(text, "", 180, TimeUnit.SECONDS);

        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        outputStream.flush();

        if (outputStream != null) {
            outputStream.close();
        }
    }


    @Autowired
    private userService userService;
    @Autowired
    private TokenUtils tokenUtils;
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){

        //验证码校验
        if(!redisTemplate.hasKey(loginUser.getVerificationCode())){
            return Result.err(Result.CODE_ERR_BUSINESS,"验证码不正确");
        }

        User user = userService.LoginUser(loginUser.getUserCode());
        log.info("用户信息:{}",user);
        if(user==null){
            return Result.err(Result.CODE_ERR_UNLOGINED,"账号不存在");
        }
        //String pwd = DigestUtils.md5DigestAsHex(user.getUserPwd().getBytes());
        String pwd = DigestUtil.hmacSign(loginUser.getUserPwd());
        log.info("输入的密码{}:",pwd);
        log.info("数据库密码:{}",user.getUserPwd());
        //String pwd = DigestUtils.md5DigestAsHex(user.getUserPwd().getBytes());
        if(!pwd.equals(user.getUserPwd())){
            return Result.err(Result.CODE_ERR_UNLOGINED,"密码错误");
        }

        if(!user.getUserState().equals(WarehouseConstants.USER_STATE_PASS)){
            return Result.err(Result.CODE_ERR_BUSINESS,"账号未审核");
        }
        CurrentUser currentUser=new CurrentUser(user.getUserId(),user.getUserCode(), user.getUserName());
        String token = tokenUtils.loginSign(currentUser, pwd);
        return Result.ok("登录成功",token);
    }

    @RequestMapping("/curr-user")
    public Result getToken(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken){
        CurrentUser currentUser = tokenUtils.getCurrentUser(clientToken);
        return Result.ok(currentUser);
    }
    @Autowired
    private AutoService autoService;

    @GetMapping("/user/auth-list")
    public Result AuthList(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken){
        CurrentUser currentUser = tokenUtils.getCurrentUser(clientToken);
        int userId = currentUser.getUserId();
        List<Auth> authById = autoService.findAuthById(userId);
        return Result.ok(authById);
    }

    @DeleteMapping("/logout")
    public Result logout(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken) {
        log.info("删除信息是:",clientToken);
        //从redis移除token
        redisTemplate.delete(clientToken);
        return Result.ok();
    }
}